# 示例业务逻辑服务 - 数据库版本
from typing import List, Optional
from sqlalchemy.orm import Session
from app.models.example import Example
from app.schemas.example import ExampleCreate, ExampleUpdate

class ExampleService:
    """示例服务类 - 使用数据库"""
    
    def create_example(self, db: Session, example_data: ExampleCreate) -> Example:
        """创建示例"""
        db_example = Example(
            name=example_data.name,
            description=example_data.description
        )
        db.add(db_example)
        db.commit()
        db.refresh(db_example)
        return db_example
    
    def get_examples(self, db: Session, skip: int = 0, limit: int = 100) -> List[Example]:
        """获取所有示例"""
        return db.query(Example).filter(Example.is_active == True).offset(skip).limit(limit).all()
    
    def get_example_by_id(self, db: Session, example_id: int) -> Optional[Example]:
        """根据ID获取示例"""
        return db.query(Example).filter(Example.id == example_id, Example.is_active == True).first()
    
    def update_example(self, db: Session, example_id: int, example_data: ExampleUpdate) -> Optional[Example]:
        """更新示例"""
        db_example = self.get_example_by_id(db, example_id)
        if not db_example:
            return None
        
        # 更新字段
        update_data = example_data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_example, field, value)
        
        db.commit()
        db.refresh(db_example)
        return db_example
    
    def delete_example(self, db: Session, example_id: int) -> bool:
        """删除示例（软删除）"""
        db_example = self.get_example_by_id(db, example_id)
        if not db_example:
            return False
        
        db_example.is_active = False
        db.commit()
        return True
    
    def count_examples(self, db: Session) -> int:
        """统计示例总数"""
        return db.query(Example).filter(Example.is_active == True).count()

# 全局服务实例
example_service = ExampleService() 